<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
class DMControlPanelTemplateHelper extends DMGenericTemplateHelper
implements DMTemplateHelper {

	const NUM_NEWS_ITEMS = 3;

	/**
	 * @param DMComment comment
	 * @return HTML table element
	 */
	public function getHtmlEditableCommentsAsTable(array $comments) {
		$tables = "";
		foreach ($comments as $c) {
			$skip = false;
			try {
				$c->getObject();
			} catch (DMUnavailableModelException $e) {
				$skip = true;
			}

			$tables .= '<table class="comments" cellpadding="0" cellspacing="2" border="0">';
			if ($skip) {
				$tables .= '<caption>Comment ID ' . $c->getID()
						. ' associated with nonexistent object.</caption>
					</table>';
			} else {
				$tables .= '<caption>
						<label>
							<input type="checkbox" name="id[]"
								value="' . DMString::websafe($c->getID()) .'">
							' . DMString::websafe($c->getTimestamp()->format('M d, Y @ g:i A')) .'
						</label>
					</caption>
					<tr>
					<th>Object:</th>
						<td><a href="' . DMString::websafe($c->getObject()->getURI(DMBridgeComponent::TemplateEngine)) . '">
							' . DMString::websafe($c->getObject()->getMetadata('title')) . '</a>
						</td>
						<td rowspan="4" style="text-align:right">
							<img src="' . DMString::websafe($c->getObject()->getThumbnailURL()) . '"
								 style="width:80px">
						</td>
					</tr>
					<tr>
						<th>Collection:</th>
						<td>' . DMString::websafe($c->getObject()->getCollection()->getName()) . '</td>
					</tr>
					<tr>
						<th>Author:</th>
						<td><input type="text" name="author[' . $c->getID() . ']"
								   style="width:60%"
								   value="' . DMString::websafe($c->getName()) . '"></td>
					</tr>
					<tr>
						<th>Email:</th>
						<td><input type="text" name="email[' . $c->getID() .']"
								   style="width:60%"
								   value="' . DMString::websafe($c->getEmail()) . '"></td>
					</tr>
					<tr>
						<th>Comment:</th>
						<td colspan="2">
							<textarea name="body[' . $c->getID() . ']"
									  style="height:120px;width:100%">'. DMString::websafe($c->getValue()) . '</textarea>
						</td>
					</tr>
				</table>';
			}
		}
		return $tables;
	}

	/**
	 * @return HTML unordered list
	 */
	public function getHtmlMainMenu() {
		$ds = DMDataStoreFactory::getDataStore();

		// build default menu
		$sections = array();

		// basic setup
		$section = new DMCPMenuSection("Basic Setup");
		$item = new DMCPMenuItem(
				"Basic Setup",
				DMInternalURI::getURIWithParams("admin/basic"));
		$section->addMenuItem($item);
		$sections[] = $section;

		// modules
		$section = new DMCPMenuSection("Modules");
		$item = new DMCPMenuItem(
				"View All",
				DMInternalURI::getURIWithParams("admin/modules"));
		$section->addMenuItem($item);
		$sections[] = $section;

		// comments
		$section = new DMCPMenuSection("Comments");
		$item = new DMCPMenuItem(
				"Configure",
				DMInternalURI::getURIWithParams("admin/comments/edit"));
		$section->addMenuItem($item);
		$num = "";
		try {
			$cq = new DMCommentQuery($ds);
			$cq->setApproved(-1);
			$cq->getSearchResults();
			$num = sprintf(" (%d)", $cq->getNumResults());
		} catch (DMException $e) {
			// do nothing
		}
		$item = new DMCPMenuItem(
				"Moderate" . $num,
				DMInternalURI::getURIWithParams("admin/comments/moderate"));
		$section->addMenuItem($item);
		$item = new DMCPMenuItem(
				"Search",
				DMInternalURI::getURIWithParams("admin/comments/search"));
		$section->addMenuItem($item);
		$item = new DMCPMenuItem(
				"Statistics",
				DMInternalURI::getURIWithParams("admin/comments/statistics"));
		$section->addMenuItem($item);
		$sections[] = $section;

		// ratings
		$section = new DMCPMenuSection("Ratings");
		$item = new DMCPMenuItem(
				"Configure",
				DMInternalURI::getURIWithParams("admin/ratings/edit"));
		$section->addMenuItem($item);
		$item = new DMCPMenuItem(
				"Statistics",
				DMInternalURI::getURIWithParams("admin/ratings/statistics"));
		$section->addMenuItem($item);
		$sections[] = $section;
		
		// tags
		$section = new DMCPMenuSection("Tags");
		$item = new DMCPMenuItem(
				"Configure",
				DMInternalURI::getURIWithParams("admin/tags/edit"));
		$section->addMenuItem($item);
		$num = "";
		try {
			$tq = new DMTagQuery($ds);
			$tq->setApproved(-1);
			$tq->getSearchResults();
			$num = sprintf(" (%d)", $tq->getNumResults());
		} catch (DMException $e) {
			// do nothing
		}
		$item = new DMCPMenuItem(
				"Moderate" . $num,
				DMInternalURI::getURIWithParams("admin/tags/moderate"));
		$section->addMenuItem($item);
		$item = new DMCPMenuItem(
				"View All",
				DMInternalURI::getURIWithParams("admin/tags"));
		$section->addMenuItem($item);
		$item = new DMCPMenuItem(
				"Statistics",
				DMInternalURI::getURIWithParams("admin/tags/statistics"));
		$section->addMenuItem($item);
		$sections[] = $section;

		// collections
		$section = new DMCPMenuSection("Collections");
		$item = new DMCPMenuItem(
				"View All",
				DMInternalURI::getURIWithParams("admin/collections"));
		$section->addMenuItem($item);
		$item = new DMCPMenuItem(
				"URL Redirection",
				DMInternalURI::getURIWithParams("admin/reference_urls"));
		$section->addMenuItem($item);
		$sections[] = $section;

		// template sets
		$section = new DMCPMenuSection("Template Sets");
		$item = new DMCPMenuItem(
				"Add",
				DMInternalURI::getURIWithParams("admin/templates/add"));
		$section->addMenuItem($item);
		$item = new DMCPMenuItem(
				"View All",
				DMInternalURI::getURIWithParams("admin/templates"));
		$section->addMenuItem($item);
		$sections[] = $section;
				
		// feeds
		$section = new DMCPMenuSection("Feeds");
		$item = new DMCPMenuItem(
				"Configure",
				DMInternalURI::getURIWithParams("admin/feeds"));
		$section->addMenuItem($item);
		$sections[] = $section;

		// CQR
		$section = new DMCPMenuSection("CQR");
		$item = new DMCPMenuItem(
				"Convert",
				DMInternalURI::getURIWithParams("admin/cqr/convert"));
		$section->addMenuItem($item);
		$sections[] = $section;

		// custom module sections
		$mm = DMModuleManager::getInstance();
		foreach ($mm->getEnabledModules() as $module) {
			if ($module instanceof DMBridgeControlPanelModule) {
				foreach ($module->getControlPanelMenuSections() as $section) {
					$section->setFromModule(true);
					$sections[] = $section;
				}
			}
		}

		// documentation
		$section = new DMCPMenuSection("Documentation");
		$item = new DMCPMenuItem(
				"User's Manual",
				DMURI::getLocalURIWithPath(
						dirname($_SERVER['PHP_SELF']) . "/doc/manual/html-chunked/index.html"));
		$section->addMenuItem($item);
		$item = new DMCPMenuItem(
				"PHP API",
				DMURI::getLocalURIWithPath(
						dirname($_SERVER['PHP_SELF']) . "/doc/php_api/html/index.html"));
		$section->addMenuItem($item);
		$item = new DMCPMenuItem(
				"HTTP API",
				DMInternalURI::getURIWithParams("api/1/doc"));
		$section->addMenuItem($item);
		$sections[] = $section;

		// done building menu data; now transform it to HTML
		$dxml = new DMDOMDocument("1.0", "utf-8");
		$dxml->loadXML("<ul/>");

		$current_route = DMHTTPRequest::getCurrent()->getURI()->getRoute();
		foreach ($sections as $section) {
			$sec_li = $dxml->createElement("li");
			$title = $dxml->createElement("span", $section->getTitle());
			$title->setAttribute("class", "accordionButton");
			$title->setAttribute("id",
					str_replace(" ", "", $section->getTitle()));
			$sec_li->appendChild($title);

			if ($section->isFromModule()) {
				$title->setAttribute("class",
						$title->getAttribute("class") . " ModuleSection");
			}
			$ul = $dxml->createElement("ul");

			$div = $dxml->createElement("div");
			$div->appendChild($ul);
			$div->setAttribute("class", "accordionPanel");

			foreach ($section->getMenuItems() as $item) {
				$item_li = $dxml->createElement("li");
				$ul->appendChild($item_li);
				$item_a = $dxml->createElement("a", $item->getTitle());
				$item_a->setAttribute("href", $item->getURI());
				// highlight the currently selected item
				if ($item->getURI() instanceof DMInternalURI) {
					$item_uri = new DMInternalURI();
					$item_uri->setParams($item->getURI()->getParams());
					if ($current_route->equals($item_uri->getRoute())) {
						$item_li->setAttribute("class", "active");
						$item_li->parentNode->parentNode->setAttribute("style",
								"display:block");
					}
				}
				$item_li->appendChild($item_a);
			}
			$sec_li->appendChild($div);
			$dxml->documentElement->appendChild($sec_li);
		}
		
		return $dxml->saveHTML($dxml->documentElement);
	}

	/**
	 * @return HTML definition list
	 */
	public function getHtmlNews() {
		$um = new DMUpdateManager(new DMHTTPRequest());
		$news = $um->getNewsItems(self::NUM_NEWS_ITEMS);
		if (!count($news)) {
			return DMLocalizedString::getString("NO_NEWS");
		}

		$dxml = new DMDOMDocument("1.0", "utf-8");
		$dxml->loadXML("<dl/>");
		$doc = $dxml->documentElement;

		foreach ($news as $ni) {
			$doc->appendChild($dt = $dxml->createElement("dt"));
			$a = $dxml->createElement("a",
				$ni->getDate()->format("Y-m-d") . ": " . $ni->getTitle());
			$a->setAttribute("href", $ni->getURL());
			$dt->appendChild($a);

			$dd = $dxml->createElement("dd",
				DMString::truncate(strip_tags($ni->getBody()), 40));
			$doc->appendChild($dd);
		}

		return $dxml->saveHTML($dxml->documentElement);
	}

	/**
	 * @return string
	 */
	public function getHtmlVersionDetail() {
		$dxml = new DMDOMDocument('1.0', 'utf-8');
		$dxml->loadXML('<dl/>');
		$doc = $dxml->documentElement;

		// control panel version
		$doc->appendChild($dxml->createElement('dt', 'dmBridge version:'));
		$doc->appendChild($dd = $dxml->createElement('dd'));
		if (DMBridgeVersion::getDmBridgeVersion()) {
			$text = DMBridgeVersion::getDmBridgeVersion();
			if (DMBridgeVersion::isNewerDmBridgeVersionAvailable(new DMHTTPRequest())) {
				$text .= ' <a href="http://digital.library.unlv.edu/software/dmbridge">(newer
					version available)</a>';
			}
			$frag = $dxml->createDocumentFragment();
			$frag->appendXML($text);
			$doc->appendChild($frag);
		} else {
			$dd->nodeValue = 'Invalid or missing VERSION.txt file.';
		}

		// config file location
		$doc->appendChild($dxml->createElement('dt', 'Config file location:'));
		$doc->appendChild($dd = $dxml->createElement('dd'));
		$dd->appendChild(
			$dxml->createElement('code', DMConfigXML::getInstance()->getFullPath()));

		// config file validity
		if (!DMConfigXML::getInstance()->isValid()) {
			$err = libxml_get_last_error();
			if ($err instanceof LibXMLError) {
				$message = sprintf('Line %d: %s', $err->line, $err->message);
				$doc->appendChild($dxml->createElement('dt', 'Config file errors:'));
				$doc->appendChild($dd = $dxml->createElement('dd', $message));
			}
		}

		return $dxml->saveHTML($dxml->documentElement);
	}

}
